﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.IO;

namespace FCMS.Mvc
{
    public class VerifyCodeResult : ActionResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            var code = GenCode(4);
            context.HttpContext.Session["CheckCode"] = code;
            CreateCheckCodeImage(code, context.HttpContext.Response);
        }

        private string GenCode(int num)
        {
            string[] source = { "X", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "X", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            string code = "";
            Random rd = new Random();
            int i;
            for (i = 0; i < num; i++)
            {
                code += source[rd.Next(0, source.Length)];

            }
            return code;

        }

        //生成验证码图片
        private void CreateCheckCodeImage(string checkCode, HttpResponseBase response)
        {
            if (string.IsNullOrEmpty(checkCode))
                throw new Exception("没有取到验证码字符串");

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 13), 20);
            Graphics g = Graphics.FromImage(image);
            try
            {
                Random random = new Random();

                g.Clear(Color.White);

                int i;
                for (i = 0; i < 30; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Gainsboro), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.MidnightBlue, Color.Green, 1.2F, true);
                g.DrawString(checkCode, font, brush, 2, 2);


                g.DrawRectangle(new Pen(Color.YellowGreen), 0, 0, image.Width - 1, image.Height - 1);


                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                byte[] buffer = ms.ToArray();
                ms.Dispose();
                response.ClearContent();
                response.ContentType = "image/jpeg";
                response.BinaryWrite(buffer);
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}
